{% extends 'base.html' %}
{% load staticfiles %}

{% block head %}
    <link rel="stylesheet" href="{% static 'AdminLTE/bower_components/datatables.net-bs/css/dataTables.bootstrap.min.css' %}">
    <link rel="stylesheet" href="{% static 'css/awesome-bootstrap-checkbox.css' %}">
    <link rel="stylesheet" href="{% static 'css/dataTables.checkboxes.css' %}">
    <link rel="stylesheet" href="{% static 'jquery-confirm/dist/jquery-confirm.min.css' %}">
    <link rel="stylesheet" href="{% static 'AdminLTE/bower_components/select2/dist/css/select2.min.css' %}">
    <link rel="stylesheet" href="{% static 'css/selectize.css' %}">
    <link rel="stylesheet" href="{% static 'css/toastr.min.css' %}">
    <style>
        /* dataTables列内容居中 */
        #db_list > tbody > tr > td {
            text-align: center;
        }

        /* dataTables表头居中 */
        #db_list > thead:first-child > tr:first-child > th {
            text-align: center;
        }

        #db_list_filter>label>input {
            width: 200px;
        }

        .form-horizontal .form-group {
            margin-right: -200px;
        }

        .has-input-error {
            border: 1px solid #dd4b39;
        }

        #searchBox .form-group > label {
            margin-top: 5px; text-align: right; padding-right: 0px; padding-left: 0px;
        }

        #searchBox .form-group > .input-group {
            position: relative;
            left: 15px;
        }

        #buttonBar button {
            margin-right: 2px;
            margin-bottom: 5px;
        }

        .error-text {
            color: #dd4b39;
        }

        .toast-vertical-center {
            top:10%;
            left:30%;
        }

        @media screen and (min-width:1200px) and (max-width:1800px){
            label[for='search_asset_nu']{
                font-size:2px;
                line-height: 12px;
            }
        }

        td div.badge{
            white-space: pre-wrap;
        }
    </style>

{% endblock %}

{% block content %}
    {% if perms.dbmanager.change_dbconfig %}
    {% include 'dbmanager/update_db_user.html' %}
    {% endif %}
    <div class="row">
        <div class="col-sm-7 pull-left" id="buttonBar"  style="margin-bottom: 3px">
            {% if perms.dbmanager.add_dbconfig %}
            <button class="btn btn-sm btn-success pull-left" data-toggle="modal" data-target="#DBModal"
                    id="add-db">
                <i class="fa fa-plus-square"></i>
                <span class="bigger-110">新增数据库</span>
            </button>
            {% endif %}
            <button class="btn btn-sm btn-info pull-left" id="advancedSearchBox">
                <i class="fa fa-search"></i>
                <span class="bigger-110">高级筛选</span>
            </button>
            <button class="btn btn-sm btn-info pull-left" style="display: none;" id="advancedSearch">
                <i class="fa fa-search"></i>
                <span class="bigger-110">点击筛选</span>
            </button>
            <button class="btn btn-sm btn-info pull-left" style="display: none;" id="refreshCondition">
                <i class="glyphicon glyphicon-trash"></i>
                <span class="bigger-110">清空筛选</span>
            </button>
            {% if perms.dbmanager.change_dbconfig or perms.dbmanager.delete_dbconfig %}
                <div class="btn-group pull-left">
                    <button type="button" class="btn btn-primary btn-sm" style="margin-right: 0;">批量操作</button>
                    <button type="button" class="btn btn-primary btn-sm dropdown-toggle" data-toggle="dropdown" aria-expanded="false">
                        <span class="caret"></span>
                    </button>
                    <ul class="dropdown-menu dropdown-menu-left" role="menu">
                        {% if perms.dbmanager.delete_dbconfig %}
                            <li><a type="button" class="btn pull-left" id="batchDelete"><i class="fa fa-trash-o"></i>批量删除</a></li>
                        {% endif %}
                        {% if perms.dbmanager.change_dbconfig %}
                            <li><a type="button" class="btn pull-left" id="batchAddUsers"><i class="fa fa-plus-square"></i>批量新增授权用户</a></li>
                            <li><a type="button" class="btn pull-left" id="batchDeleteUsers"><i class="fa fa-trash"></i>批量取消授权用户</a></li>
                            <li><a type="button" class="btn pull-left" id="batchAddGroup"><i class="fa fa-plus-square"></i>批量新增授权组</a></li>
                            <li><a type="button" class="btn pull-left" id="batchDeleteGroup"><i class="fa fa-trash"></i>批量取消授权组</a></li>
                        {% endif %}
                    </ul>
                </div>
            {% endif %}
            <div class="btn-group pull-left">
                <button type="button" class="btn btn-primary btn-sm" style="margin-right: 0;">批量导出</button>
                <button type="button" class="btn btn-primary btn-sm dropdown-toggle" data-toggle="dropdown" aria-expanded="false">
                    <span class="caret"></span>
                </button>
                <ul class="dropdown-menu dropdown-menu-left" role="menu">
                    {% if user.is_superuser %}
                    <li><a type="button" class="btn pull-left" id="downloadDBConfig"><i class="fa fa-download"></i>导出检索的数据库配置</a></li>
                    <li><a type="button" class="btn pull-left" id="downloadSelectedDBConfig"><i class="fa fa-download"></i>导出勾选的数据库配置</a></li>
                    {% endif %}
                </ul>
            </div>
        </div>
        
        <form id="searchForm">
            <div class="col-md-12 col-lg-12 col-xs-12 pull-left" style="margin: 3px;">
                <div id="searchBox" style="width: 99%; display: none;">
                    <div class="clearfix visible-xs"></div>
                    <div class="col-md-6 col-lg-4 col-xs-12" style="margin: 3px 0;">
                        <div class="form-group">
                            <label for="search_db_ip" class="col-lg-4 col-md-4 col-xs-3 control-label">管理IP</label>
                            <div class="col-lg-8 col-md-8 col-xs-9">
                              <input type="text" class="form-control" id="search_db_ip" name="search_db_ip">
                            </div>
                        </div>
                    </div>
                    <div class="col-md-6 col-lg-4 col-xs-12" style="margin: 3px 0;">
                        <div class="form-group">
                            <label for="search_asset_nu" class="col-lg-3 col-md-4 col-xs-3 control-label">资产编号/资产名称</label>
                            <div class="col-lg-9 col-md-8 col-xs-9">
                              <input type="text" class="form-control" id="search_asset_nu" name="search_asset_nu">
                            </div>
                        </div>
                    </div>
                    <div class="col-md-6 col-lg-4 col-xs-12" style="margin: 3px 0;">
                        <div class="form-group">
                            <label for="search_db_user" class="col-lg-3 col-md-4 col-xs-3 control-label">数据库账号</label>
                            <div class="col-lg-9 col-md-8 col-xs-9">
                              <input type="text" class="form-control" id="search_db_user" name="search_db_user">
                            </div>
                        </div>
                    </div>
                    <div class="col-md-6 col-lg-4 col-xs-12" style="margin: 3px 0;">
                        <div class="form-group">
                            <label for="search_db_type" class="col-lg-4 col-md-4 col-xs-3 control-label">数据库类型</label>
                            <div class="col-lg-8 col-md-8 col-xs-9">
                                <select class="form-control" id="search_db_type" style="width: 100%;" name="search_db_type">
                                    <option value=""></option>
                                    {% for protocol in db_type_ %}
                                        <option value="{{ protocol.0 }}">{{ protocol.1 }}</option>
                                    {% endfor %}
                                </select>
                            </div>
                        </div>
                    </div>
                    <div class="col-md-6 col-lg-4 col-xs-12" style="margin: 3px 0;">
                        <div class="form-group">
                            <label for="search_asset_product" class="col-lg-3 col-md-4 col-xs-3 control-label">产品名称</label>
                            <div class="col-lg-9 col-md-8 col-xs-9">
                                <select id="search_asset_product" style="display: none;" name="search_asset_product"></select>
                            </div>
                        </div>
                    </div>
                    <div class="col-md-6 col-lg-4 col-xs-12" style="margin: 3px 0;">
                        <div class="form-group">
                            <label for="search_asset_environment" class="col-lg-3 col-md-4 col-xs-3 control-label">设备环境</label>
                            <div class="col-lg-9 col-md-8 col-xs-9">
                                <select class="form-control" id="search_asset_environment" style="width: 100%;" name="search_asset_environment">
                                    <option value=""></option>
                                    {% for choice in environment_choice_ %}
                                        <option value="{{ choice.0 }}">{{ choice.1 }}</option>
                                    {% endfor %}
                                </select>
                            </div>
                        </div>
                    </div>
                    <div class="clearfix visible-xs"></div>
                </div>
            </div>
        </form>
        
        <!--dataTable-->
        <div class="col-xs-12">
            <div class="box" style="min-width: 1100px;">
                <div class="box-body">
                    <table id="db_list" class="table table-bordered table-striped" style="width:100%; table-layout: fixed;">
                        <thead>
                            <tr>
                                <th></th>
                                <th>序号</th>
                                <th>资产名称/资产编号</th>
                                <th>地址</th>
                                <th>库类型</th>
                                <th>账号</th>
                                <th>库名称/实例名</th>
                                {% if perms.dbmanager.add_dbconfig or perms.dbmanager.view_db_password or perms.dbmanager.change_dbconfig or perms.dbmanager.delete_dbconfig %}<th>操作</th>{% endif %}
                            </tr>
                        </thead>
                    </table>
                </div>
            </div>

            {% if perms.dbmanager.add_dbconfig %}
            <div class="modal fade" id="DBModal" tabindex="-1" role="dialog" aria-labelledby="DBModalLabel"
                 aria-hidden="true">
                <div class="modal-dialog">
                    <div class="modal-content">
                        <div class="modal-header">
                            <button type="button" class="close" data-dismiss="modal" aria-hidden="true">
                                &times;
                            </button>
                            <h4 class="modal-title" id="DBModalLabel">
                                新增数据库
                            </h4>
                        </div>
                        <div class="modal-body">
                            <form id="db_info" class="main form-horizontal">
                                <fieldset>
                                    <div class="form-group col-sm-12">
                                        <label for="db_server" class="col-sm-3 control-label">对应资产<span class="text-red">*</span></label>
                                        <div class="col-sm-9">
                                            <select class="form-control" name="db_server" id="db_server"
                                                    style="width: 100%;">
                                            </select>
                                        </div>
                                    </div>

                                    <div class="form-group col-sm-12">
                                        <label for="db_type" class="col-sm-3 control-label">数据库类型<span class="text-red">*</span></label>
                                        <div class="col-sm-9">
                                            <select class="form-control select2" name="db_type"
                                                    id="db_type" style="width: 100%;" onchange="dbType();">
                                                {% for db_type in db_type_ %}
                                                    <option value="{{ db_type.0 }}">{{ db_type.1 }}</option>
                                                {% endfor %}
                                            </select>
                                        </div>
                                    </div>

                                    <div class="form-group col-sm-12" style="display: none;">
                                        <label for="db_oracle_type" class="col-sm-3 control-label">连接类型<span class="text-red">*</span></label>
                                        <div class="col-sm-9">
                                            <select class="form-control" name="db_oracle_type"
                                                    id="db_oracle_type" style="width: 100%;" onchange="dbOracleType();">
                                                {% for db_oracle_type in db_oracle_type_ %}
                                                    <option value="{{ db_oracle_type.0 }}">{{ db_oracle_type.1 }}</option>
                                                {% endfor %}
                                            </select>
                                        </div>
                                    </div>

                                    <div class="form-group col-sm-12">
                                        <label for="db_port" class="col-sm-3 control-label">数据库端口<span class="text-red">*</span></label>
                                        <div class="col-sm-9">
                                            <input type="number" class="form-control" name="db_port" min="1" max="99999" oninput="if(this.value=='0'){this.value='';}else{this.value=this.value.replace(/[^0-9]/g,'')};if(this.value.length>5){this.value=this.value.slice(0,5)}"
                                                   id="db_port"/>
                                        </div>
                                    </div>

                                    <div class="form-group col-sm-12">
                                        <label for="db_name" class="col-sm-3 control-label">数据库名称/实例名</label>
                                        <div class="col-sm-9">
                                            <input type="text" class="form-control" name="db_name"
                                                   id="db_name"/>
                                        </div>
                                    </div>

                                    <div class="form-group col-sm-12">
                                        <label for="db_user" class="col-sm-3 control-label">数据库账号<span class="text-red">*</span></label>
                                        <div class="col-sm-9">
                                            <input type="text" class="form-control" name="db_user"
                                                   id="db_user"/>
                                        </div>
                                    </div>

                                    <div class="form-group col-sm-12">
                                        <label for="db_password" class="col-sm-3 control-label">数据库密码<span class="text-red">*</span></label>
                                        <div class="col-sm-9">
                                            <input type="password" class="form-control" name="db_password"
                                                   id="db_password"/>
                                        </div>
                                    </div>

                                    <div class="form-group col-sm-12">
                                        <label for="db_code" class="col-sm-3 control-label">数据库编码</label>
                                        <div class="col-sm-9">
                                            <input type="text" class="form-control" name="db_code"
                                                   id="db_code" placeholder="例如：utf8"/>
                                        </div>
                                    </div>

                                    <div class="form-group col-sm-12">
                                        <label for="db_belong_user" class="col-sm-3 control-label">所属用户</label>
                                        <div class="col-sm-9">
                                            <select class="form-control select2" id="db_belong_user"
                                                    multiple="multiple" name="db_belong_user"
                                                    style="width: 100%;">
                                                {% for user in users %}
                                                    <option value="{{ user.id }}">{{ user.username }}</option>
                                                {% endfor %}
                                            </select>
                                        </div>
                                    </div>

                                    <div class="form-group col-sm-12">
                                        <label for="db_group" class="col-sm-3 control-label">使用组</label>
                                        <div class="col-sm-9">
                                            <select class="form-control select2" name="db_group" multiple
                                                    id="db_group" style="width: 100%;">
                                                {% for group in groups %}
                                                    <option value="{{ group.id }}">{{ group.name }}</option>
                                                {% endfor %}
                                            </select>
                                        </div>
                                    </div>

                                    <div class="form-group col-sm-12">
                                        <label for="db_memo" class="col-sm-3 control-label">备注</label>
                                        <div class="col-sm-9">
                                        <textarea class="form-control" name="db_memo"
                                                  id="db_memo"></textarea>
                                        </div>
                                    </div>
                                </fieldset>
                            </form>
                        </div>
                        <div class="modal-footer">
                            <button type="button" class="btn btn-default" data-dismiss="modal">关闭</button>
                            <button type="button" class="btn btn-primary" id="db_ops">添加</button>
                        </div>
                    </div><!-- /.modal-content -->
                </div><!-- /.modal -->
            </div>
            {% endif %}
        </div>
    </div>
    <!-- /.row -->

{% endblock %}


{% block js %}
    <script src="{% static 'AdminLTE/bower_components/select2/dist/js/select2.full.min.js' %}"></script>
    <script src="{% static 'AdminLTE/bower_components/datatables.net/js/jquery.dataTables.min.js' %}"></script>
    <script src="{% static 'AdminLTE/bower_components/datatables.net-bs/js/dataTables.bootstrap.min.js' %}"></script>
    <script src="{% static 'js/dataTables.checkboxes.min.js' %}"></script>
    <script src="{% static 'jquery-confirm/dist/jquery-confirm.min.js' %}"></script>
    <script src="{% static 'js/selectize.min.js' %}"></script>
    <script src="{% static 'js/bootbox.js' %}"></script>
    <script src="{% static 'js/toastr.min.js' %}"></script>
    <script>
        $(function () {
            toastr.options = {
                "closeButton": true, //是否显示关闭按钮
                "positionClass": "toast-vertical-center",//弹出窗的位置
            }

            var db_table = $('#db_list').DataTable({
                language: {
                   "sProcessing": "处理中...",
                   "sLengthMenu": "显示 _MENU_ 项结果",
                   "sZeroRecords": "没有匹配结果",
                   "sInfo": "显示第 _START_ 至 _END_ 项结果，共 _TOTAL_ 项",
                   "sInfoEmpty": "显示第 0 至 0 项结果，共 0 项",
                   "sInfoFiltered": "(由 _MAX_ 项结果过滤)",
                   "sInfoPostFix": "",
                   "sSearch": "快速搜索:",
                   "searchPlaceholder": "管理IP 资产编号/资产名称 账号",
                   "sUrl": "",
                   "sEmptyTable": "表中数据为空",
                   "sLoadingRecords": "载入中...",
                   "sInfoThousands": ",",
                   "oPaginate": {
                       "sFirst": "首页",
                       "sPrevious": "上页",
                       "sNext": "下页",
                       "sLast": "末页"
                   },
                   "oAria": {
                       "sSortAscending": ": 以升序排列此列",
                       "sSortDescending": ": 以降序排列此列"
                   }
               },
                columnDefs: [
                    {
                        'targets': 0,
                        'render': function (data, type, row, meta) {
                            if (type === 'display') {
                                data = '<div class="checkbox"><input type="checkbox" class="dt-checkboxes" value="'+row.id+'"><label></label></div>';
                            }
                            return data;
                        },
                        'orderable': false,
                        'checkboxes': {
                            'selectRow': true,
                        }
                    },
                    {
                        'targets': 1,
                        'render': function (data, type, row, meta) {
                            return row.id;
                        },
                    },
                    {
                        'targets': 2,
                        'render': function (data, type, row, meta) {
                            var asset_environment = row.db_server.asset_environment
                            var asset_nu = row.db_server.asset_nu
                            switch (asset_environment){
                                case 0:
                                    data = '<div class="badge bg-blue">'+asset_nu+'</div>\n'
                                    break;
                                case 1:
                                    data = '<div class="badge bg-teal">'+asset_nu+'</div>\n'
                                    break;
                                case 2:
                                    data = '<div class="badge bg-green">'+asset_nu+'</div>\n'
                                    break;
                                case 3:
                                    data = '<div class="badge bg-purple">'+asset_nu+'</div>\n'
                                    break;
                                default:
                                    data = '<div class="badge bg-yellow">'+asset_nu+'</div>\n'
                            }
                            return data
                        },
                    },
                    {
                        'targets': 3,
                        'render': function (data, type, row, meta) {
                            return row.db_server.db_IP
                        },
                    },
                    {
                        'targets': 4,
                        'render': function (data, type, row, meta) {
                            return row.db_type[1]
                        },
                    },
                    {
                        'targets': 5,
                        'render': function (data, type, row, meta) {
                            return row.db_user;
                        },
                    },
                    {
                        'targets': 6,
                        'render': function (data, type, row, meta) {
                            return row.db_name
                        },
                    },
                    {% if perms.dbmanager.add_dbconfig or perms.dbmanager.view_db_password or perms.dbmanager.change_dbconfig or perms.dbmanager.delete_dbconfig %}
                    {
                        'targets': 7,
                        'render': function (d, type, row, meta) {
                            data = ''
                            {% if perms.dbmanager.change_dbconfig %}
                            data += '<button type="button" class="btn btn-success btn-xs modify" data-toggle="modal" data-target="#updateDBModal" onclick="updateDBConig('+row.id+')">详细/更新</button>\n'
                            {% endif %}
                            {% if perms.dbmanager.delete_dbconfig %}
                                data += '<button type="button" class="btn btn-danger btn-xs delete" onclick="deleteDBConig('+row.id+')">删除</button>&nbsp;'
                            {% endif %}
                            data += '<div class="btn-group">\n' +
                                '<button type="button" class="btn btn-primary btn-xs">更多</button>\n' +
                                '<button type="button" class="btn btn-primary btn-xs dropdown-toggle" data-toggle="dropdown" aria-expanded="false">\n' +
                                '<span class="caret"></span>\n' +
                                '</button>\n' +
                                '<ul class="dropdown-menu  dropdown-menu-right" role="menu">\n'
                            {% if perms.dbmanager.add_dbconfig or perms.dbmanager.view_db_password %}
                            data += '<li><a onclick="searchDBPassword('+row.id+');">查看库密码</a></li>\n'
                            {% endif %}
                            {% if perms.dbmanager.change_dbconfig %}
                            data += '<li><a onclick="updateDBPassword('+row.id+');">修改库密码</a></li>\n'
                            {% endif %}
                            data += '</ul></div>\n'
                            return data;
                        },
                        'orderable': false,
                    }{% endif %}
                ],
                "infoCallback": function(settings,start,end,max,total,pre) {
                    var api = this.api();
                    var pageInfo = api.page.info();
                    return "共"+pageInfo.pages +"页,当前显示"+ start + "到" + end + "条记录" + ",共有"+ total + "条记录";
                },
                "order": [[1, "desc"]],
                "processing": true,
                "serverSide": true,
                "ajax": function (data, callback, settings) {
                    //console.log(data)
                    //封装请求参数
                    var param = {};
                    param.page_size = data.length;//页面显示记录条数，在页面显示每页显示多少项的时候
                    param.start = data.start;//开始的记录序号
                    param.page = (data.start / data.length)+1;//当前页码
                    param.search = data.search.value;
                    var order = data.order[0]
                    var order_key = data.columns[order.column].data
                    $("#searchForm").serializeArray().forEach(function(el){
                        param[el['name'].slice(7,)]= el['value']
                    })
                    if(order.dir=="asc"){
                        param.ordering = order_key
                    } else {
                        param.ordering = '-'+order_key
                    }
                    //ajax请求数据
                    $.ajax({
                        type: "GET",
                        url: "/api/dbconfiglist/",
                        cache: false,  //禁用缓存
                        data: param,  //传入组装的参数
                        dataType: "json",
                        success: function (result) {
                            //console.log(result);
                            var returnData = {};
                            returnData.draw = data.draw;//这里直接自行返回了draw计数器,应该由后台返回
                            returnData.recordsTotal = result.count;//返回数据全部记录
                            returnData.recordsFiltered = result.count;//后台不实现过滤功能，每次查询均视作全部结果
                            returnData.data = result.results;//返回的数据列表
                            //console.log(returnData);
                            callback(returnData);
                        }
                    });
                },
                columns: [
                    { "data": "id", "width": "30px" },
                    { "data": "id", "width": "40px" },
                    { "data": "asset_nu" },
                    { "data": "db_IP" },
                    { "data": "db_type", },
                    { "data": "db_user", },
                    { "data": "db_name", },
                    {% if perms.dbmanager.add_dbconfig or perms.dbmanager.view_db_password or perms.dbmanager.change_dbconfig or perms.dbmanager.delete_dbconfig %}{ "width": "200px" },{% endif %}
                ],
            });

            $("#advancedSearchBox").click(function () {
                $("#refreshCondition").show()
                $("#advancedSearchBox").hide()
                $("#advancedSearch").show()
                $("#searchBox").show()
                toastr.info("使用SHIFT+回车键开启快捷筛选。")
            });

            $("#refreshCondition").click(function () {
                $("#searchBox input,#searchBox select").val("")
                $('#search_asset_product').selectize()[0].selectize.clear()
            })

            $("#advancedSearch").click(function () {
                db_table.draw(true);
            });

            $(document).keypress(function (e) {
                if(e.shiftKey&&e.keyCode==13){
                    db_table.draw(true);
                }
            })
        
            {% if user.is_superuser %}
            $("#downloadDBConfig").click(function () {
                var data = db_table.ajax.params();
                param={}
                param.search = data.search.value;
                var order = data.order[0]
                var order_key = data.columns[order.column].data
                $("#searchForm").serializeArray().forEach(function(el){
                    param[el['name']]= el['value']
                })
                if(order.dir=="asc"){
                    param.ordering = order_key
                } else {
                    param.ordering = '-'+order_key
                }
                param.asset_type = 'server'
                downloadServerFile("/api/export/dbs/", $.param(param), '数据库配置列表.xlsx')
                $.alert({
                    title: 'Tips',
                    type: 'green',
                    content: '只会导出检索的所有数据库配置（含账户/密码，且不分页）！',
                })
            })

            $("#downloadSelectedDBConfig").click(function () {
                var checkedID = checked()
                if (checkedID.length === 0) {
                    $.alert({
                        title: 'Tips',
                        type: 'red',
                        content: '请选择要导出的数据库配置！',
                    })
                    return
                }
                var data = db_table.ajax.params();
                param={}
                var order = data.order[0]
                var order_key = data.columns[order.column].data
                if(order.dir=="asc"){
                    param.ordering = order_key
                } else {
                    param.ordering = '-'+order_key
                }
                var ids = JSON.stringify(checkedID)
                param.ids = ids
                param.asset_type = 'server'
                downloadServerFile("/api/export/dbs/", $.param(param), '数据库配置列表.xlsx')
                $.alert({
                    title: 'Tips',
                    type: 'green',
                    content: '只会导出勾选的数据库配置（含账户/密码）！',
                })
            })
            {% endif %}
        });

        // Initialize Select2 Elements
        $(function () {
            $('#search_asset_product').selectize({
                valueField: 'id',
                labelField: 'text',
                searchField: 'text',
                load: function(query, callback) {
                    $.ajax({
                        url: '/project/find_product_name/',
                        data: {
                            product_name: query
                        },
                        dataType: 'json',
                        type: 'GET',
                        error: function() {
                            callback();
                        },
                        success: function(res) {
                            callback(res.results);
                        }
                    });
                }
            });

            $('.select2').select2({
                allowClear: true
            })

            $('#db_server').select2({
                allowClear: true,
                ajax: {
                    url: '/assets/find_hosted_on/',
                    dataType: 'json',
                    data: function (params) {
                        params.offset = 6
                        params.page = params.page || 1
                        var query = {
                            search: params.term,
                            page: params.page,
                            offset: params.offset,
                        }
                        return query;
                    },
                    processResults: function (data, params) {
                        var page = params.page || 1
                        return {
                            results: data.results,
                            pagination: {
                                more: (page*params.offset) < data.total_count
                            }
                        };
                    },
                    cache: true
                  },
                minimumInputLength: 2,
                templateResult: formatRepo,
                templateSelection: formatRepoSelection,
                placeholder: '查询IP地址 或 项目编号/名称'
            });
        });

        function formatRepo (repo) {
            if (repo.loading) {
                return repo.text;
            }
            var $container = $("<div class='select2-result-repository clearfix'>" +
                  "<div class='select2-result-repository-element'>" + repo.text +
                "</div></div>");
            return $container;
        }

        function formatRepoSelection (repo) {
            return repo.text;
        }

        // 处理在modal中select2当选框无法搜索的问题
        $.fn.modal.Constructor.prototype.enforceFocus = function () {
        };

        let db_ops = $('#db_ops');
        let update_db_ops = $('#update_db_ops');

        function clearLabel(){
            $('label[for=db_name] span').remove()
            $('label[for=db_code] span').remove()
            $('#db_name').attr('placeholder','')
        }

        function dbType(){
            clearLabel()
            dbTypeReset()
            cleanError()
            let db_type = $('#db_type').val()
            if(db_type == '0'){
                $('#db_port').val('3306')
                $('label[for=db_name]').append('<span class="text-red">*</span>')
                $('label[for=db_code]').append('<span class="text-red">*</span>')
            } else if (db_type == '1'){
                $('label[for=db_oracle_type]').parent().show()
                $('#db_port').val('1521')
                $('label[for=db_name]').append('<span class="text-red">*</span>')
            }
        }

        function dbTypeView(){
            $('label[for=update_db_name] span').remove()
            $('label[for=update_db_code] span').remove()
            $('label[for=update_db_port]').parent().show()
            $('label[for=update_db_oracle_type]').parent().hide()
            $('#update_db_name').attr('placeholder','')
            cleanError()
            let db_type = $('#update_db_type').val()
            if(db_type == '0'){
                $('label[for=update_db_name]').append('<span class="text-red">*</span>')
                $('label[for=update_db_code]').append('<span class="text-red">*</span>')
            } else if (db_type == '1'){
                $('label[for=update_db_name]').append('<span class="text-red">*</span>')
                $('label[for=update_db_oracle_type]').parent().show()
                if($('#update_db_oracle_type').val() == '1'){
                    $('label[for=update_db_port]').parent().hide()
                    $('#update_db_name').attr('placeholder','格式形如 10.3.0.11:1521/fzcbebr')
                }
            }
        }

        function dbTypeReset(){
            $('#db_port').val('')
            $('#db_name').val('')
            $('#db_code').val('')
            $('label[for=db_oracle_type]').parent().hide()
            $('#db_oracle_type').val('0')
            $('label[for=db_port]').parent().show()
        }

        function dbOracleType(){
            cleanError()
            $('label[for=db_port]').parent().toggle()
            $('#db_name').val('')
            if($('#db_oracle_type').val()==1){
                $('#db_name').attr('placeholder','格式形如 10.3.0.11:1521/fzcbebr')
                $('#db_port').val('')
            } else {
                $('#db_name').attr('placeholder','')
                $('#db_port').val('1521')
            }
        }

        function dbOracleUpdateType(){
            cleanError()
            $('label[for=update_db_port]').parent().toggle()
            $('#update_db_name').val('')
            if($('#update_db_oracle_type').val()==1){
                $('#update_db_name').attr('placeholder','格式形如 10.3.0.11:1521/fzcbebr')
                $('#update_db_port').val('')
            } else {
                $('#update_db_name').attr('placeholder','')
                $('#update_db_port').val('1521')
            }
        }

        function addErrorMessage(errors) {
            $.each(errors, function(name, value){
                if(name == 'non_field_errors'){
                    $('#db_name').after('<span class="help-block">该数据库名称/实例名已经存在!</span>')
                    $('#db_name').parent().parent().addClass('has-error')
                    $('#db_user').after('<span class="help-block">该用户已经存在!</span>')
                    $('#db_user').parent().parent().addClass('has-error')
                } else if(name == 'db_server') {
                    $('#db_server').parent().append('<span class="help-block">'+value[0]+'</span>')
                    $('#db_server').next().addClass('has-input-error').parent().parent().addClass('has-error')
                } else if(name == 'db_type') {
                    $('#db_type').parent().append('<span class="help-block">'+value[0]+'</span>')
                    $('#db_type').next().addClass('has-input-error').parent().parent().addClass('has-error')
                } else {
                    $.each(value, function(i, v){
                        $('#'+name).after('<span class="help-block">'+v+'</span>')
                    })
                    $('#'+name).parent().parent().addClass('has-error')
                }
            })
        }

        function addUpdateErrorMessage(errors) {
            $.each(errors, function(name, value){
                if(name == 'non_field_errors'){
                    $('#update_db_name').after('<span class="help-block">该数据库名称/实例名已经存在!</span>')
                    $('#update_db_name').parent().parent().addClass('has-error')
                    $('#update_db_user').after('<span class="help-block">该用户已经存在!</span>')
                    $('#update_db_user').parent().parent().addClass('has-error')
                } else {
                    $.each(value, function(i, v){
                        $('#update_'+name).after('<span class="help-block">'+v+'</span>')
                    })
                    $('#update_'+name).parent().parent().addClass('has-error')
                }
            })
        }

        function cleanError(){
            $('.has-input-error').removeClass('has-input-error')
            $('.has-error').removeClass('has-error')
            $('.help-block').remove()
        }

        {% if perms.dbmanager.add_dbconfig %}
        // 新增数据库
        $('#add-db').on('click', function () {
            clearLabel();
            cleanError();
            document.getElementById('db_info').reset();
            $(".select2").val('').trigger('change');
            $("#db_server").val('').trigger('change');
            db_ops.unbind('click').on('click', function () {
                cleanError()
                if(!$('#db_type').val()){
                    addErrorMessage({db_type: ['该字段不能为空。']})
                    return
                }
                if(!$('#db_name').val() && $('#db_type').val() != 2){
                    addErrorMessage({db_name: ['该字段不能为空。']})
                    return
                }
                if(!$('#db_code').val() && $('#db_type').val() == 0){
                    addErrorMessage({db_code: ['该字段不能为空。']})
                    return
                }
                var data = {
                            db_server: $('#db_server').val(),
                            db_type: $('#db_type').val(),
                            db_port: $('#db_port').val(),
                            db_name: $('#db_name').val(),
                            db_user: $('#db_user').val(),
                            db_code: $('#db_code').val(),
                            db_password: $('#db_password').val(),
                            db_belong_user: $('#db_belong_user').val(),
                            db_oracle_type: $('#db_oracle_type').val(),
                            db_group: $('#db_group').val(),
                            db_memo: $('#db_memo').val()
                        }
                $.ajax({
                    url: "/api/dbconfig/",
                    type: 'POST',
                    data: JSON.stringify(data),
                    contentType: "application/json",
                    dataType: 'json',
                    success: function (res) {
                        $('#DBModal').modal('hide')
                        $.alert({
                            title: 'Tips',
                            type: 'green',
                            content: '新增成功！',
                        })
                        $('#db_list').DataTable().draw(true);

                    },
                    error: function (response) {
                        addErrorMessage(response.responseJSON)
                        $.alert({
                            title: 'Tips',
                            type: 'red',
                            content: '请修改错误。',
                        })
                    }
                })
            })
        });
        {% endif %}

        {% if perms.dbmanager.change_dbconfig %}
        // 更新数据库
        function updateDBConig(db_id) {
            document.getElementById('update_db_info').reset();
            $(".select2").val('').trigger('change');
            $("#update_db_server").val('').trigger('change');
            $.get('/api/dbconfig/' + db_id + '/', function (data) {
                $('#update_db_type').val(data.db_type).trigger('change');
                $('#update_db_server').val(data.db_server);
                $('#update_db_asset_nu').val(data.asset_nu);
                $('#update_db_IP').val(data.db_IP);
                $('#update_db_port').val(data.db_port);
                $('#update_db_code').val(data.db_code);
                $('#update_db_name').val(data.db_name);
                $('#update_db_user').val(data.db_user);
                $('#update_db_oracle_type').val(data.db_oracle_type);
                $('#update_db_belong_user').val(data.db_belong_user).trigger('change');
                $('#update_db_group').val(data.db_group).trigger('change');
                $('#update_db_memo').val(data.db_memo);
                dbTypeView();
            });
            update_db_ops.unbind('click').on('click', function () {
                cleanError()
                if(!$('#update_db_name').val() && $('#update_db_type').val() != 2){
                    addUpdateErrorMessage({db_name: ['该字段不能为空。']})
                    return
                }
                if(!$('#update_db_code').val() && $('#update_db_type').val() == 0){
                    addUpdateErrorMessage({db_code: ['该字段不能为空。']})
                    return
                }
                var data = {
                            id: db_id,
                            db_port: $('#update_db_port').val(),
                            db_name: $('#update_db_name').val(),
                            db_user: $('#update_db_user').val(),
                            db_code: $('#update_db_code').val(),
                            db_belong_user: $('#update_db_belong_user').val(),
                            db_oracle_type: $('#update_db_oracle_type').val(),
                            db_group: $('#update_db_group').val(),
                            db_memo: $('#update_db_memo').val()
                        }
                $.ajax({
                    url: '/api/dbconfig/' + db_id + '/',
                    type: 'PATCH',
                    data: JSON.stringify(data),
                    contentType: "application/json",
                    dataType: 'json',
                    success: function (res) {
                        $('#updateDBModal').modal('hide')
                        $.alert({
                            title: 'Tips',
                            type: 'green',
                            content: '修改成功！',
                        })
                        $('#db_list').DataTable().draw(true);
                    },
                    error: function (response) {
                        addUpdateErrorMessage(response.responseJSON)
                        $.alert({
                            title: 'Tips',
                            type: 'red',
                            content: '请修改错误。',
                        })
                    }
                })
            });
        };
        {% endif %}

        {% if perms.dbmanager.delete_dbconfig %}
        // 删除数据库
        function deleteDBConig(pk) {
            $.confirm({
                title: 'Tips',
                content: '确定要删除这条记录么？',
                type: 'red',
                buttons: {
                    Ok: function () {
                        $.ajax({
                            url: '/api/dbconfig/' + pk + '/',
                            method: 'DELETE',
                            success: function (res) {
                                $.alert({
                                    title: 'Tips',
                                    type: 'green',
                                    content: '删除成功！',
                                })
                                $('#db_list').DataTable().draw(true);
                            },
                            error: function (data) {
                                $.alert({
                                    title: 'Tips',
                                    type: 'red',
                                    content: '删除失败！',
                                })
                            }
                        })
                    },
                    Cancel: function () {
                        //
                    }
                }
            });
        };
        {% endif %}

        {% if perms.dbmanager.add_dbconfig or perms.dbmanager.view_db_password %}
        function searchDBPassword(db_user_id){
            var content
            $.ajax({
                url: '/db_config/search_db_password/' + db_user_id + '/',
                async: false,
                type: 'GET',
                success: function (result) {
                    content = '<p class="form-control-static" id="search_db_password" style="width:100%;">当前密码：'+result.results.db_password+'</p>'
                },
                error: function (response) {
                    console.log(response.responseText)
                    toastr.error('获取失败！')
                }
            });
            bootbox.dialog({
                title: '密码信息',
                size: "small",
                message: content,
                buttons: {
                    cancel: {
                        label: '关闭',
                        className: 'btn-danger',
                    },
                }
            })
        }
        {% endif %}

        {% if perms.dbmanager.change_dbconfig %}
        function updateDBPassword(db_user_id){
            bootbox.confirm({
                title: '重置密码',
                size: "small",
                message: '<div style="margin-top: 5px;"><input type="password" class id="update_db_password" style="width: 100%;" placeholder="请输入新的密码"></p></div>',
                buttons: {
                    confirm: {
                        label: '确认',
                        className: 'btn-success'
                    },
                    cancel: {
                        label: '取消',
                        className: 'btn-danger'
                    }
                },
                callback: function (result) {
                    var flag = true
                    if(result==true){
                        cleanError()
                        $('.error-text').remove()
                        $.ajax({
                            url: '/api/dbconfig/' + db_user_id + '/',
                            type: 'PATCH',
                            async: false,
                            data: JSON.stringify({
                                db_password: $("#update_db_password").val()
                            }),
                            dataType: 'json',
                            contentType: "application/json",
                            success: function (result) {
                                toastr.success("修改成功！")
                            },
                            error: function (response) {
                                error = response.responseJSON
                                if(error.hasOwnProperty('db_password')){
                                    $('#update_db_password').after('<span class="error-text">'+error.db_password+'</span>')
                                    $('#update_db_password').addClass('has-input-error')
                                }
                                flag = false
                            }
                        });
                        return flag
                    }
                }
            })
        }
        {% endif %}

        function checked() {
            let checkedID = [];
            var table = $('#db_list').DataTable()
            var rows = $('#db_list tbody>tr>td>div>input[type=checkbox]')
            $.each(rows, function (index, row) {
                if(row.checked == true){
                   checkedID.push(row.value)
                }
            })
            return checkedID;
        }
        // 批量删除
        {% if perms.dbmanager.delete_dbconfig %}
        $("#batchDelete").click(function () {
            let checkedID = checked();
            if (checkedID.length === 0) {
                $.alert({
                    title: 'Tips',
                    type: 'red',
                    content: '请选择要删除的连接！',
                })
            } else {
                var count = 0
                $.confirm({
                    title: 'Tips',
                    content: '确定要删除这些连接么？',
                    type: 'red',
                    buttons: {
                        Ok: function () {
                            for (let i = 0; i < checkedID.length; i++) {
                                $.ajax({
                                    url: '/api/dbconfig/' + checkedID[i] + '/',
                                    method: 'DELETE',
                                    async: false,
                                    success: function () {
                                        count +=1
                                    }
                                })
                            }
                            $.confirm({
                                title: 'Tips',
                                content: '成功删除'+count+'个连接！',
                                type: 'green',
                                buttons: {
                                    Ok: function () {
                                        $('#db_list').DataTable().draw(true)
                                    },
                                }
                            })
                        },
                        Cancel: function () {
                            // close
                        }
                    }
                })
            }
        });
        {% endif %}

        {% if perms.dbmanager.change_dbconfig %}
            $("#batchAddUsers").click(function () {
                let checkedID = checked();
                if (checkedID.length === 0) {
                    $.alert({
                        title: 'Tips',
                        type: 'red',
                        content: '请选择待修改的数据库配置！',
                    })
                } else {
                    var count = 0
                    var msg = '<select class="form-control" id="batch_add_db_belong_user"\n' +
                        ' multiple="multiple" name="batch_add_db_belong_user" style="width: 100%;" data-placeholder="请选择">\n' +
                        ' {% for user in users %}\n'+
                        ' <option value="{{ user.id }}">{{ user.username }}</option>\n' +
                        ' {% endfor %}</select>'
                    bootbox.confirm({
                        title: '批量新增授权用户',
                        size: "small",
                        message: msg,
                        buttons: {
                            confirm: {
                                label: '确认',
                                className: 'btn-success'
                            },
                            cancel: {
                                label: '取消',
                                className: 'btn-danger'
                            }
                        },
                        callback: function (result) {
                            if(result==true){
                                cleanError()
                                $('.error-text').remove()
                                if($("#batch_add_db_belong_user").val().length == 0){
                                    toastr.error('请修改错误！')
                                    $('#batch_add_db_belong_user').next().addClass('has-input-error').parent().after('<span class="error-text">该字段不能为空。</span>')
                                    return false
                                }
                                var count = 0
                                 for (let i = 0; i < checkedID.length; i++) {
                                    $.ajax({
                                        url: '/db_config/batch_change_db_belong_user/',
                                        type: 'POST',
                                        async: false,
                                        data: JSON.stringify({
                                            type: 'add',
                                            db_id: checkedID[i],
                                            db_belong_user: $("#batch_add_db_belong_user").val()
                                        }),
                                        contentType: "application/json",
                                        success: function (result) {
                                            count += 1
                                        }
                                    });
                                }
                                $.confirm({
                                    title: 'Tips',
                                    content: '成功修改'+count+'个数据库！',
                                    type: 'green',
                                    buttons: {
                                        Ok: function () {
                                            $('#db_list').DataTable().draw(true)
                                        },
                                    }
                                })
                            }
                        }
                    })
                }
                $("#batch_add_db_belong_user").select2()
            })

            $("#batchDeleteUsers").click(function () {
                let checkedID = checked();
                if (checkedID.length === 0) {
                    $.alert({
                        title: 'Tips',
                        type: 'red',
                        content: '请选择待修改的数据库配置！',
                    })
                } else {
                    var count = 0
                    var msg = '<select class="form-control" id="batch_delete_db_belong_user"\n' +
                        ' multiple="multiple" name="batch_delete_db_belong_user" style="width: 100%;" data-placeholder="请选择">\n' +
                        ' {% for user in users %}\n'+
                        ' <option value="{{ user.id }}">{{ user.username }}</option>\n' +
                        ' {% endfor %}</select>'
                    bootbox.confirm({
                        title: '批量取消授权用户',
                        size: "small",
                        message: msg,
                        buttons: {
                            confirm: {
                                label: '确认',
                                className: 'btn-success'
                            },
                            cancel: {
                                label: '取消',
                                className: 'btn-danger'
                            }
                        },
                        callback: function (result) {
                            if(result==true){
                                cleanError()
                                $('.error-text').remove()
                                if($("#batch_delete_db_belong_user").val().length == 0){
                                    toastr.error('请修改错误！')
                                    $('#batch_delete_db_belong_user').next().addClass('has-input-error').parent().after('<span class="error-text">该字段不能为空。</span>')
                                    return false
                                }
                                var count = 0
                                for (let i = 0; i < checkedID.length; i++) {
                                    $.ajax({
                                        url: '/db_config/batch_change_db_belong_user/',
                                        type: 'POST',
                                        async: false,
                                        data: JSON.stringify({
                                            type: 'delete',
                                            db_id: checkedID[i],
                                            db_belong_user: $("#batch_delete_db_belong_user").val()
                                        }),
                                        contentType: "application/json",
                                        success: function (result) {
                                            count += 1
                                        }
                                    });
                                }
                                $.confirm({
                                    title: 'Tips',
                                    content: '成功修改'+count+'个数据库！',
                                    type: 'green',
                                    buttons: {
                                        Ok: function () {
                                            $('#db_list').DataTable().draw(true)
                                        },
                                    }
                                })
                            }
                        }
                    })
                }
                $("#batch_delete_db_belong_user").select2()

            })

            $("#batchAddGroup").click(function () {
                let checkedID = checked();
                if (checkedID.length === 0) {
                    $.alert({
                        title: 'Tips',
                        type: 'red',
                        content: '请选择待修改的数据库配置！',
                    })
                } else {
                    var count = 0
                    var msg = '<select class="form-control" id="batch_add_db_group"\n' +
                        ' multiple="multiple" name="batch_add_db_group" style="width: 100%;" data-placeholder="请选择">\n' +
                        ' {% for group in groups %}\n'+
                        ' <option value="{{ group.id }}">{{ group.name }}</option>\n' +
                        ' {% endfor %}</select>'
                    bootbox.confirm({
                        title: '批量新增授权组',
                        size: "small",
                        message: msg,
                        buttons: {
                            confirm: {
                                label: '确认',
                                className: 'btn-success'
                            },
                            cancel: {
                                label: '取消',
                                className: 'btn-danger'
                            }
                        },
                        callback: function (result) {
                            if(result==true){
                                cleanError()
                                $('.error-text').remove()
                                if($("#batch_add_db_group").val().length == 0){
                                    toastr.error('请修改错误！')
                                    $('#batch_add_db_group').next().addClass('has-input-error').parent().after('<span class="error-text">该字段不能为空。</span>')
                                    return false
                                }
                                var count = 0
                                for (let i = 0; i < checkedID.length; i++) {
                                    $.ajax({
                                        url: '/db_config/batch_change_db_group/',
                                        type: 'POST',
                                        async: false,
                                        data: JSON.stringify({
                                            type: 'add',
                                            db_id: checkedID[i],
                                            db_group: $("#batch_add_db_group").val()
                                        }),
                                        contentType: "application/json",
                                        success: function (result) {
                                            count += 1
                                        }
                                    });
                                }
                                $.confirm({
                                    title: 'Tips',
                                    content: '成功修改'+count+'个数据库！',
                                    type: 'green',
                                    buttons: {
                                        Ok: function () {
                                            $('#db_list').DataTable().draw(true)
                                        },
                                    }
                                })
                            }
                        }
                    })
                }
                $("#batch_add_db_group").select2()
            })

            $("#batchDeleteGroup").click(function () {
                let checkedID = checked();
                if (checkedID.length === 0) {
                    $.alert({
                        title: 'Tips',
                        type: 'red',
                        content: '请选择待修改的数据库配置！',
                    })
                } else {
                    var count = 0
                    var msg = '<select class="form-control" id="batch_delete_db_group"\n' +
                        ' multiple="multiple" name="batch_delete_db_group" style="width: 100%;" data-placeholder="请选择">\n' +
                        ' {% for group in groups %}\n'+
                        ' <option value="{{ group.id }}">{{ group.name }}</option>\n' +
                        ' {% endfor %}</select>'
                    bootbox.confirm({
                        title: '批量取消授权组',
                        size: "small",
                        message: msg,
                        buttons: {
                            confirm: {
                                label: '确认',
                                className: 'btn-success'
                            },
                            cancel: {
                                label: '取消',
                                className: 'btn-danger'
                            }
                        },
                        callback: function (result) {
                            if(result==true){
                                cleanError()
                                $('.error-text').remove()
                                if($("#batch_delete_db_group").val().length == 0){
                                    toastr.error('请修改错误！')
                                    $('#batch_delete_db_group').next().addClass('has-input-error').parent().after('<span class="error-text">该字段不能为空。</span>')
                                    return false
                                }
                                var count = 0
                                for (let i = 0; i < checkedID.length; i++) {
                                    $.ajax({
                                        url: '/db_config/batch_change_db_group/',
                                        type: 'POST',
                                        async: false,
                                        data: JSON.stringify({
                                            type: 'delete',
                                            db_id: checkedID[i],
                                            db_group: $("#batch_delete_db_group").val()
                                        }),
                                        contentType: "application/json",
                                        success: function (result) {
                                            count += 1
                                        }
                                    });
                                }
                                $.confirm({
                                    title: 'Tips',
                                    content: '成功修改'+count+'个数据库！',
                                    type: 'green',
                                    buttons: {
                                        Ok: function () {
                                            $('#db_list').DataTable().draw(true)
                                        },
                                    }
                                })
                            }
                        }
                    })
                }
                $("#batch_delete_db_group").select2()
            })
        {% endif %}

        function downloadServerFile(url, param, filename){
            let xhr = new XMLHttpRequest();
            xhr.open('POST', url+"?"+param);
            xhr.responseType = 'blob';
            xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
            xhr.setRequestHeader('X-CSRFToken', '{{ csrf_token }}');
            xhr.onload = function () {
                if (this.status === 200) {
                    let blob = this.response;
                    let reader = new FileReader();
                    reader.readAsDataURL(blob);
                    reader.onload = function (e) {
                        let a = document.createElement('a');
                        a.download = filename;
                        a.href = e.target.result;
                        a.click();
                        $(a).remove();
                    }
                }
            };
            xhr.send(param)
        }

    </script>

{% endblock %}

